import datetime

from django.db import models


from sportsground.utils.baseModels import BaseModels, IntegerChoices


class OrderVip(BaseModels):
    class Meta():
        db_table = 'order_vip'
        verbose_name = '会员卡订单'
        verbose_name_plural = verbose_name

    class State(IntegerChoices):
        Paying = 1, "待支付"
        Payed = 2, "支付成功"
        PayTimeout = 5, "支付失败"
        # Drawback = 6, "退款"

    order = models.ForeignKey(to="Order", on_delete=models.CASCADE, verbose_name="总订单")
    vip = models.ForeignKey(to="Venue.Vip", on_delete=models.CASCADE, verbose_name="会员卡")
    state = models.IntegerField(choices=State.choices, verbose_name="状态")

    price = models.FloatField(verbose_name="价格")
    number = models.IntegerField(verbose_name="数量")
    getTime = models.DateTimeField(null=True, verbose_name="收货时间")
    message = models.CharField(max_length=200, verbose_name="留言")

    # drawback = models.ForeignKey(to="Drawback",null=True, on_delete=models.CASCADE, verbose_name="退款")

    def capitalInfo(self):
        """ 资金流水账 """
        return {
            "oid": self.order_id,
            "id": self.id,
            "vipId": self.vip_id,
            "price": self.price,
            "number": self.number,
            "createTime": self.createTime
        }
    def Info(self):
        self.checkTimeout()
        return {
            "id": self.id,
            "vip": self.vip.Info(),
            "state": self.state,
            "price": self.price,
            "number": self.number,
            "getTime": self.getTime,
            "message": self.message,
            "createTime": self.createTime,
        }

    @classmethod
    def create(cls, user, vip, message=''):
        from User.models import Order
        venue = vip.venue
        order = Order.create(user, venue, type=Order.OrderType.Vip)
        orderVip = cls(order=order, vip=vip, state=cls.State.Paying, price=vip.price, number=1, message=message)
        orderVip.save()
        return order

    def pay(self, user):
        """ 支付 """
        from User.models import UserVip
        if self.state == self.State.Paying:
            self.state = self.State.Payed
            self.save()
            UserVip.create(user, vip=self.vip)

    def checkTimeout(self):
        """ 超时 """
        if self.state == self.State.Paying:
            over = self.createTime + datetime.timedelta(minutes=30)
            now = datetime.datetime.now()
            if over < now:
                self.state = self.State.PayTimeout
                self.save()

